<?php
class OrdersController extends AppController {

	var $name = 'Orders';

	function index() {
		$this->Order->recursive = 0;
		$this->set('orders', $this->paginate());
	}

	function admin_index() {
		$this->Order->recursive = 0;
		$orders = $this->paginate();
		$this->loadModel('OrderItem');
		$this->OrderItem->recursive = 1;
		$count = 0;
		foreach ($orders as $order){
			$conditions = array('OrderItem.order_id'=>$order['Order']['id']);
			$OrderItems = $this->OrderItem->find('all',array('conditions'=>$conditions));
			$prices=0;
			foreach ($OrderItems as $OrderItem){
				$prices = $OrderItem['OrderItem']['quanlity']*$OrderItem['Item']['price'];
			}
			$orders[$count]['Order']['prices']=$prices;
			$count++;
		}
		$this->set('orders', $orders);
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid order', true));
			$this->redirect(array('action' => 'index'));
		}
		$order = $this->Order->read(null, $id);		
		$this->loadModel('OrderItem');
		$this->OrderItem->recursive = 1;
		$conditions = array('OrderItem.order_id'=>$order['Order']['id']);
		$OrderItems = $this->OrderItem->find('all',array('conditions'=>$conditions));
		$prices=0;
		$count = 0;		
		foreach ($OrderItems as $OrderItem){
			// set order item detail
			$order['OrderItem'][$count]['item_name'] = $OrderItem['Item']['item_name'];
			$order['OrderItem'][$count]['total_items_price'] = $OrderItem['Item']['price']*$OrderItem['OrderItem']['quanlity'];
			$prices += $order['OrderItem'][$count]['total_items_price'];
			$count++;
		}
		$order['Order']['prices']=$prices;
		$this->set('order',$order);
		
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for order', true));
			$this->redirect(array('action'=>'index'));
		}
		$order = $this->Order->read($id);
		if ($this->Order->delete($id)) {			
			// đặt lại trạng thái sử dụng của bàn
			$this->loadModel('Table');
	  		$this->Table->read(null,$order['Order']['table_id']);
	  		$this->Table->set('used',0);
	  		$this->Table->save();
	  		
			$this->Session->setFlash(__('Order deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Order was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid order', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			// order ko được thanh toán khi chưa prepared
			if($this->data['Order']['paid']==1 && $this->data['Order']['prepared']==0){
				$this->Session->setFlash('prepared order first', true);
				$this->redirect(array('admin'=>true,'action' => 'index'));
			}
			if ($this->Order->save($this->data)) {				
				// đổi trạng thái sử dụng của table thành chưa sử dụng nếu order được paid
				$order = $this->Order->read(null,$id);
				//print_r($order);
				$this->loadModel('Table');
				$table= $this->Table->read(null,$order['Order']['table_id']);
				//print_r($table);
				if($this->data['Order']['paid']==1){
					// nếu bàn được thanh toán					
					$this->Table->set('used',0);
				}else{
					// nếu bàn được set chưa thanh toán
					$this->Table->set('used',1);
				}
				$this->Table->save();
				$this->Session->setFlash(__('The order has been saved', true));
				$this->redirect(array('admin'=>true,'action' => 'index'));
			} else {
				$this->Session->setFlash(__('The order could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Order->read(null, $id);
		}
		$employees = $this->Order->Employee->find('list');
		$tables = $this->Order->Table->find('list');
		$this->set(compact('employees', 'tables'));
	}
	
	function admin_paid($id){
		$this->autoRender = false;
		if (!$id) {
			$this->Session->setFlash('invalidate order',true);
			$this->redirect(array('admin'=>true,'action' => 'index'));
		}
		$order = $this->Order->read(null,$id);
		// order phải được prepared trước khi thanh toán
		//print_r($order);
		if($order['Order']['prepared']==0){
			$this->Session->setFlash('prepared order first',true);
			$this->redirect(array('admin'=>true,'action' => 'index'));
		}
		$this->Order->set('paid',1);
		$this->Order->save();
		// thay đổi trạng thái sử dụng của table 
		$this->loadModel('Table');
		$this->Table->read(null,$order['Order']['table_id']);
		$this->Table->set('used',0);
		$this->Table->save();
		// redirect đến trang index
		$this->redirect(array('admin'=>true,'action' => 'index'));
	}
	
	function admin_prepared($id){
		$this->autoRender=false;
		if (!$id) {
			$this->Session->setFlash('invalidate order',true);
			$this->redirect(array('admin'=>true,'action' => 'index'));
		}
		$this->Order->read(null,$id);
		$this->Order->set('prepared',1);
		$this->Order->save();
		$this->redirect(array('admin'=>true,'action' => 'index'));
	}
	//-----------------------------------------------------------
	
	// add order from mobile -------------------------------------
	function admin_add() {
  		$this->autoRender=false;
		if(!isset($_POST['orderXml'])){
			return 'null';
		}
		echo '<?xml version="1.0" encoding="UTF-8"?>';
		echo '<response>';
		$status = 1;
		$message = '';
		$dataXML = $_POST['orderXml'];
		$xml = simplexml_load_string($dataXML);
  		foreach($xml->children() as $child){
  			if($child->getName()=='items'){
  				$countItems = 0;
  				// variable save all items array
  				$items;
  				foreach ($child as $item){
  					// get id of items
  					$attributesItem = $item->attributes();
  					$idItem = (String)$attributesItem['id'];
  					// get quality and note of item
  					foreach ($item->children() as $itemSpecify){
  						$itemSpecifies[$itemSpecify->getName()] = (String)$itemSpecify;
  					}
  					$items[$countItems] = array_merge(array('item_id'=>$idItem),$itemSpecifies);
  					unset($itemSpecifies);
  					//$items[$countItems]=implode(array('id'=>$idItem), $itemSpecifies);
  					$countItems++;
  				}
  				$order['items']=$items;
  			}else{
  				$order[$child->getName().'_id'] = (String)$child;
  			}
  		}
  		if(!isset($countItems) || $countItems == 0){
  			$status = 0;
  			$message = "Đơn hàng chưa chọn món";
  			echo '<status>'.$status.'</status>';
  			echo '<message>'.$message.'</message>';
  			echo '</response>';
  			return ;
  		}
  		// nếu table hiện đang có order chưa thanh toán thì không cho đặt order mới
  		$check = $this->Order->find('all',array(
  			'conditions'=>array(
  				'Order.table_id'=>$order['table_id'],
  				'Order.paid'=>'0'
  			),
  		));
  		// nếu bàn đang có order chưa thanh toán thì báo lỗi
  		if(count($check)> 0){
  			$status = 0;
  			$message = "Bàn chưa thanh toán. Không thể đặt thêm đơn hàng";
  			echo '<status>'.$status.'</status>';
  			echo '<message>'.$message.'</message>';
  			echo '</response>';
  			return ;
  		}
  		//print_r($order);
  		// save data -------------------------------------
  		// save order into order table
  		$orderDB=array();
  		$orderDB['Order']['employee_id'] = $order['employee_id'];
  		$orderDB['Order']['order_time']=DboSource::expression('NOW()');
  		$orderDB['Order']['table_id'] = $order['table_id'];
  		// transaction
  		$orderDataSource = $this->Order->getDataSource();
  		$orderDataSource->begin($this->Order);
  		
  		$this->Order->create();
  		$DBResult = $this->Order->save($orderDB);
  		// đặt lại trạng thái sử dụng của bàn
  		$this->loadModel('Table');
  		$this->Table->read(null,$orderDB['Order']['table_id']);
  		$this->Table->set('used',1);
  		$this->Table->save();
  		if(!$DBResult){
  			//roll back db
  			$orderDataSource->rollback($this->Order);  
  			// set response			
  			$status = 0;
  			$message = "Lỗi csdl";
  			echo '<status>'.$status.'</status>';
  			echo '<message>'.$message.'</message>';
  			echo '</response>';
  			return ;
  		}
  		$order_seved_id = $this->Order->id;
  		//echo 'order_id :'.$order_seved_id;
  		//echo 'order_items_id :';
  		// save order_items for order
  		
  		$this->loadModel('OrderItem');
  		$OrderItemDataSource = $this->OrderItem->getDataSource();
  		$OrderItemDataSource->begin($this->OrderItem);
  		foreach ($order['items'] as $item){
  			// save each item to db
  			$order_itemsDB=array();
  			$order_itemsDB['order_id'] = $order_seved_id;
  			$order_itemsDB['item_id'] = $item['item_id'];
  			$order_itemsDB['quanlity'] = $item['quanlity'];
  			if(!empty($item['note']))
  				$order_itemsDB['note'] = $item['note'];
  			// save item
  			$this->OrderItem->create();
  			$DBResult = $this->OrderItem->save($order_itemsDB);
	  		if(!$DBResult){
	  			//roll back db
  				$orderDataSource->rollback($this->Order); 
	  			$OrderItemDataSource->rollback($this->OrderItem); 
	  			// set response			
	  			$status = 0;
	  			$message = "Lỗi csdl";
	  			echo '<status>'.$status.'</status>';
	  			echo '<message>'.$message.'</message>';
	  			echo '</response>';
	  			return ;
	  		}
  			//echo $this->OrderItem->id;
  		}
  		// save to database
	  	$OrderItemDataSource->commit($this->OrderItem); 
  		$orderDataSource->commit($this->Order);
  		echo '<status>'.$status.'</status>';
  		echo '</response>';
	}
	
	
	
	// edit order -----------------------------------------	
	function admin_medit(){
  		$this->autoRender=false;
		if(!isset($_POST['orderXml'])){
			return 'null';
		}
		echo '<?xml version="1.0" encoding="UTF-8"?>';
		echo '<response>';
		$status = 1;
		$message = '';
		$dataXML = $_POST['orderXml'];
		$xml = simplexml_load_string($dataXML);
  		foreach($xml->children() as $child){
  			if($child->getName()=='items'){
  				$countItems = 0;
  				// variable save all items array
  				$items;
  				foreach ($child as $item){
  					// get id of items
  					$attributesItem = $item->attributes();
  					$idItem = (String)$attributesItem['id'];
  					// get quality and note of item
  					foreach ($item->children() as $itemSpecify){
  						$itemSpecifies[$itemSpecify->getName()] = (String)$itemSpecify;
  					}
  					$items[$countItems] = array_merge(array('item_id'=>$idItem),$itemSpecifies);
  					unset($itemSpecifies);
  					//$items[$countItems]=implode(array('id'=>$idItem), $itemSpecifies);
  					$countItems++;
  				}
  				$order['items']=$items;
  			}else{
  				$order[$child->getName().'_id'] = (String)$child;
  			}
  		}
  		if(!isset($countItems) || $countItems == 0){
  			$status = 0;
  			$message = "Đơn hàng chưa chọn món";
  			echo '<status>'.$status.'</status>';
  			echo '<message>'.$message.'</message>';
  			echo '</response>';
  			return ;
  		}
  		// get order id
  		$this->Order->recursive = 0;
  		$currentOrder = $this->Order->find('first',
  			array(
  				'conditions'=>array(
  					'Order.table_id'=>$order['table_id'],
  					'Order.paid'=>'0'
  				)
  			)
  		);
  		
  		$this->loadModel('OrderItem');
  		// delete all order_items of order thay have id = $currentOrder[id]
  		$this->OrderItem->deleteAll(
  			array('OrderItem.order_id'=>$currentOrder['Order']['id'])
  		);
  		// save order_items for order  		
  		$OrderItemDataSource = $this->OrderItem->getDataSource();
  		$OrderItemDataSource->begin($this->OrderItem);
  		foreach ($order['items'] as $item){
  			// save each item to db
  			$order_itemsDB=array();
  			$order_itemsDB['order_id'] = $currentOrder['Order']['id'];
  			$order_itemsDB['item_id'] = $item['item_id'];
  			$order_itemsDB['quanlity'] = $item['quanlity'];
  			if(!empty($item['note']))
  				$order_itemsDB['note'] = $item['note'];
  			// save item
  			$this->OrderItem->create();
  			$DBResult = $this->OrderItem->save($order_itemsDB);  		
	  		if(!$DBResult){
	  			//roll back db
	  			$OrderItemDataSource->rollback($this->OrderItem); 
	  			// set response			
	  			$status = 0;
	  			$message = "Lỗi csdl";
	  			echo '<status>'.$status.'</status>';
	  			echo '<message>'.$message.'</message>';
	  			echo '</response>';
	  			return ;
	  		}
  			//echo $this->OrderItem->id;
  		}
  		// save to database
	  	$OrderItemDataSource->commit($this->OrderItem); 
  		echo '<status>'.$status.'</status>';
  		echo '</response>';
	}
	
	// xóa order dựa vào id của table
	function admin_mdelete(){
		$this->autoRender=false;
		$tableid = $this->params['pass'][2];
		if (!$tableid) {
			return;
		}
		// lấy order có id của bàn là $tableid và chưa trả tiền
		$currentOrder = $this->Order->find('first',
  			array(
  				'conditions'=>array(
  					'Order.table_id'=>$tableid,
  					'Order.paid'=>'0'
  				)
  			)
  		);
  		if(count($currentOrder) == 0) return;
		// delete order
		if($this->Order->delete($currentOrder['Order']['id'],false)){
			// đặt lại trạng thái sử dụng của bàn
			$this->loadModel('Table');
	  		$this->Table->read(null,$currentOrder['Order']['table_id']);
	  		$this->Table->set('used',0);
	  		$this->Table->save();
		}
		/*
		 * xóa order theo id của order
		// get order
		$order = $this->Order->read(null,$id);
		// delete order
		$this->Order->delete($id,false);
		// đặt lại trạng thái sử dụng của bàn
		$this->loadModel('Table');
  		$this->Table->read(null,$order['Order']['table_id']);
  		$this->Table->set('used',0);
  		$this->Table->save();
  		*/
	}
}
?>
